"use client"

import { motion } from "framer-motion"
import { Clock, Users, Trophy, Star } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card"
import Link from "next/link"

import { useState, useEffect } from "react"
import { getImageUrl, needsProxy } from "@/utils/image-utils"

interface HackathonData {
  id: number | string
  title: string
  platform: string
  prize?: string
  prize_pool?: string
  prize_currency?: string
  deadline?: string
  end_date?: string
  start_date?: string
  submission_deadline?: string
  participants?: number
  participants_count?: number
  image?: string
  banner_image?: string
  tags?: string[]
  difficulty: string
  submissions?: number
  teams?: number
  type?: string
}

interface HackCardProps {
  hackathon: HackathonData
  featured?: boolean
  urgent?: boolean
}

export function HackCard({ hackathon, featured, urgent }: HackCardProps) {
  const [imageError, setImageError] = useState(false)
  const [imageLoading, setImageLoading] = useState(true)

  // 使用图片工具函数获取正确的图片URL
  const imageUrl = getImageUrl(hackathon.image, hackathon.banner_image, "/default-competition.svg")
  const originalImageUrl = hackathon.image || hackathon.banner_image
  const defaultImageUrl = "/default-competition.svg"
  
  // 当图片URL改变时重置错误状态
  useEffect(() => {
    if (imageUrl !== defaultImageUrl) {
      setImageError(false)
      setImageLoading(true)
    }
  }, [imageUrl, defaultImageUrl])

  const getPlatformColor = (platform: string) => {
    switch (platform.toLowerCase()) {
      case "kaggle":
        return "text-[#20BEFF]"
      case "天池":
        return "text-[#FF6A00]"
      case "devpost":
        return "text-[#0A0E2E]"
      case "google":
        return "text-[#4285F4]"
      case "microsoft":
        return "text-[#00BCF2]"
      case "openai":
        return "text-[#10A37F]"
      default:
        return "text-purple-400"
    }
  }

  const getDifficultyColor = (difficulty: string) => {
    if (!difficulty) {
      return "bg-gray-500/20 text-gray-400"
    }
    switch (difficulty.toLowerCase()) {
      case "beginner":
        return "bg-green-500/20 text-green-400"
      case "intermediate":
        return "bg-yellow-500/20 text-yellow-400"
      case "advanced":
        return "bg-red-500/20 text-red-400"
      default:
        return "bg-gray-500/20 text-gray-400"
    }
  }

  const deadline = hackathon.deadline || hackathon.end_date || ""
  const participants = hackathon.participants || hackathon.participants_count || 0
  const tags = hackathon.tags || []
  const prize = hackathon.prize || (hackathon.prize_pool && hackathon.prize_currency ? `${hackathon.prize_currency} ${hackathon.prize_pool}` : "待定")
  
  // 添加调试日志
  console.log('=== HackCard Debug Info ===')
  console.log('Competition:', hackathon.title)
  console.log('Original Image URL:', originalImageUrl)
  console.log('Processed Image URL:', imageUrl)
  console.log('Image Error State:', imageError)
  console.log('Image Loading State:', imageLoading)
  console.log('Needs Proxy:', originalImageUrl ? needsProxy(originalImageUrl) : false)
  console.log('API Base URL:', process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000')
  console.log('==========================')
  
  // 获取竞赛的实际状态
  const getCompetitionStatus = () => {
    const now = new Date()
    const startDate = hackathon.start_date ? new Date(hackathon.start_date) : null
    const endDate = hackathon.end_date ? new Date(hackathon.end_date) : null
    const submissionDeadline = hackathon.submission_deadline ? new Date(hackathon.submission_deadline) : null
    
    // 如果没有开始时间，返回未知状态
    if (!startDate) {
      return { status: 'unknown', label: '未知状态', color: 'bg-gray-500/20 text-gray-400' }
    }
    
    // 检查是否即将开始
    if (now < startDate) {
      return { status: 'upcoming', label: '即将开始', color: 'bg-blue-500/20 text-blue-400' }
    }
    
    // 检查是否已经结束
    if (endDate && now > endDate) {
      return { status: 'ended', label: '已结束', color: 'bg-red-500/20 text-red-400' }
    }
    
    // 竞赛正在进行中
    if (now >= startDate) {
      // 如果有提交截止时间
      if (submissionDeadline) {
        if (now <= submissionDeadline) {
          return { status: 'submission_open', label: '可提交', color: 'bg-green-500/20 text-green-400' }
        } else {
          return { status: 'submission_closed', label: '提交截止', color: 'bg-orange-500/20 text-orange-400' }
        }
      } else {
        // 没有提交截止时间，只要在开始和结束时间之间就是进行中
        return { status: 'ongoing', label: '进行中', color: 'bg-green-500/20 text-green-400' }
      }
    }
    
    // 默认状态
    return { status: 'unknown', label: '未知状态', color: 'bg-gray-500/20 text-gray-400' }
  }
  
  const competitionStatus = getCompetitionStatus()
  
  // 修复截止时间计算逻辑
  const calculateDaysLeft = (deadlineStr: string) => {
    if (!deadlineStr) return 0
    
    try {
      // 处理不同的日期格式
      let deadlineDate: Date
      
      // 如果是ISO格式的字符串，直接解析
      if (deadlineStr.includes('T') || deadlineStr.includes('Z')) {
        deadlineDate = new Date(deadlineStr)
      } else {
        // 如果是简单的日期格式，添加时间部分
        deadlineDate = new Date(deadlineStr + 'T23:59:59')
      }
      
      // 检查日期是否有效
      if (isNaN(deadlineDate.getTime())) {
        return 0
      }
      
      const now = new Date()
      const diffTime = deadlineDate.getTime() - now.getTime()
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      
      return diffDays
    } catch (error) {
      console.error('Error calculating days left:', error)
      return 0
    }
  }
  
  const daysLeft = calculateDaysLeft(deadline)

  return (
    <motion.div whileHover={{ y: -5, scale: 1.02 }} transition={{ duration: 0.2 }}>
      <Card
        className={`glass border-0 overflow-hidden h-full ${
          featured ? "ring-2 ring-yellow-400/50" : ""
        } ${urgent ? "ring-2 ring-red-400/50" : ""}`}
      >
        <CardHeader className="p-0">
          <div className="relative">
            <div className="relative w-full h-48 bg-gray-800 overflow-hidden">
              {imageLoading && (
                <div className="absolute inset-0 flex items-center justify-center bg-gray-800">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-400"></div>
                </div>
              )}
              {/* 使用普通img标签 */}
              <img
                src={imageError ? defaultImageUrl : imageUrl}
                alt={hackathon.title}
                className="w-full h-full object-cover"
                onLoad={() => {
                  setImageLoading(false)
                  console.log('Image loaded successfully:', hackathon.title, 'URL:', imageUrl)
                }}
                onError={(e) => {
                  console.log('Image failed to load:', hackathon.title, 'URL:', imageUrl)
                  console.log('Error details:', e)
                  const originalUrl = hackathon.image || hackathon.banner_image
                  if (originalUrl && needsProxy(originalUrl)) {
                    console.log('Proxied image failed to load. Original URL:', originalUrl)
                    console.log('Trying fallback to default image')
                  }
                  setImageError(true)
                  setImageLoading(false)
                }}
              />
            </div>
            <div className="absolute top-3 left-3">
              <Badge className={`${getPlatformColor(hackathon.platform)} bg-black/50`}>{hackathon.platform}</Badge>
            </div>
            <div className="absolute top-3 right-3 flex flex-col gap-2">
              <Badge className={getDifficultyColor(hackathon.difficulty)}>{hackathon.difficulty}</Badge>
            </div>
            {/* 状态显示移到更明显的位置 */}
            <div className="absolute bottom-3 right-3">
              <Badge className={`${competitionStatus.color} font-semibold text-sm px-3 py-1 shadow-lg`}>
                {competitionStatus.label}
              </Badge>
            </div>
            {featured && (
              <div className="absolute bottom-3 left-3">
                <Badge className="bg-yellow-500/20 text-yellow-400">
                  <Star className="w-3 h-3 mr-1" />
                  精选
                </Badge>
              </div>
            )}
            {urgent && (
              <div className="absolute bottom-3 left-3">
                <Badge className="bg-red-500/20 text-red-400 animate-pulse">
                  <Clock className="w-3 h-3 mr-1" />
                  紧急
                </Badge>
              </div>
            )}
          </div>
        </CardHeader>

        <CardContent className="p-4">
          <h3 className="font-semibold text-lg mb-2 line-clamp-2 hover:text-blue-400 transition-colors">
            <Link href={`/competitions/${hackathon.id}`}>{hackathon.title}</Link>
          </h3>

          <div className="flex items-center justify-between text-sm text-gray-400 mb-3">
            <div className="flex items-center gap-1">
              <Trophy className="w-4 h-4" />
              <span className="font-medium text-green-400">{prize}</span>
            </div>
            <div className="flex items-center gap-1">
              <Users className="w-4 h-4" />
              <span>{participants.toLocaleString()}</span>
            </div>
          </div>

          {/* 时间信息显示 */}
          <div className="bg-gray-800/50 rounded-lg p-3 mb-3 space-y-2">
            {hackathon.start_date && (
              <div className="flex items-center gap-2 text-sm">
                <Clock className="w-4 h-4 text-blue-400" />
                <span>开始时间:</span>
                <span className="font-medium">
                  {new Date(hackathon.start_date).toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric'
                  })}
                </span>
              </div>
            )}
            {(hackathon.submission_deadline || hackathon.end_date) && (
              <div className="flex items-center gap-2 text-sm">
                <Clock className="w-4 h-4 text-orange-400" />
                <span>截止时间:</span>
                <span className="font-medium">
                  {new Date(hackathon.submission_deadline || hackathon.end_date || '').toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric'
                  })}
                </span>
              </div>
            )}
          </div>

          <div className="flex flex-wrap gap-1 mb-3">
            {tags.slice(0, 3).map((tag) => (
              <Badge key={tag} variant="outline" className="text-xs">
                {tag}
              </Badge>
            ))}
            {tags.length > 3 && (
              <Badge variant="outline" className="text-xs">
                +{tags.length - 3}
              </Badge>
            )}
          </div>
        </CardContent>

        <CardFooter className="p-4 pt-0 flex gap-2">
          <Link href={`/competitions/${hackathon.id}`} className="flex-1">
            <Button variant="outline" size="sm" className="w-full bg-transparent">
              查看详情
            </Button>
          </Link>
          <Link href="/lobby">
            <Button
              size="sm"
              className="bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600"
            >
              开黑
            </Button>
          </Link>
        </CardFooter>
      </Card>
    </motion.div>
  )
}
